// pages/Home/VehicleSearch/VehicleSearch.js
import { queryTravelVehicleParamTitle , queryTravelVehicleParamCont , queryTravelVehicleIdByParamContId , queryTravelVehicleInfo , queryTravelVehicleClassify } from '../../../api/vehicle';
const regeneratorRuntime = require('../../../common/runtime');
import { throttle } from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    rentCarStartYear: '',
    rentCarEndYear: '',
    rentCarStartDate: '',
    rentCarStartTime: '',
    rentCarEndDate: '',
    rentCarEndTime: '',
    itemTitle: '快速选车',
    option1: [
      { text: '推荐排序', value: 0 },
      { text: '低价排序（总价）', value: 1 },
    ],
    value1: 0,
    paramTitleList: [],
    paramTitleId: '', // 车辆参数标题ID
    paramContList: [],
    paramContId: [], // 车辆参数内容ID
    showGoodsBtmDom: false,
    scrollTop: 0,
    activeKey: 0,
    sort: 'sort',
    order: '',
    vehicleIds: '',
    isHot: '', // 是否热门
    classificationId: '', // 分类ID
    classifyIndex: 0,
    classifyList: [], // 分类列表
    dataList: [],
    page: 0,
    isReachBottom: false,
    noMore: false,
    loading: false,
    loadingFailed: false,
    refresher: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      rentCarStartDate: wx.getStorageSync('rentCarStartDate'),
      rentCarStartTime: wx.getStorageSync('rentCarStartTime'),
      rentCarEndDate: wx.getStorageSync('rentCarEndDate'),
      rentCarEndTime: wx.getStorageSync('rentCarEndTime'),
    })
    this._queryTravelVehicleParamTitle();
    this.getClassify();
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let _this = this;
    wx.createSelectorQuery().select('.cont').boundingClientRect(res => {
      console.log(res,'分类块')
      _this.setData({
        scrollHeight: res.height,
      })
    }).exec();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    let _this = this;
    _this.initData();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          _this.setData({
            refresher: false
          })
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    console.log('上拉加载')
    if(this.data.isReachBottom){
      this._queryTopUpOrderForm()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 获取车辆参数标题
  _queryTravelVehicleParamTitle(){
    let _this = this;
    queryTravelVehicleParamTitle({size: 99})
    .then(async res => {
      if(res.success){
        // if(res.data.content.length > 0){
        //   _this._queryTravelVehicleParamCont();
        // }
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          item.children = await _this._queryTravelVehicleParamCont({titleId: item.id});
        }
        console.log(res.data.content,'content');
        _this.setData({
          paramTitleList: res.data.content,
          paramTitleId: res.data.content.length > 0 ? res.data.content[0].id : '',
        })
        _this.initDataList();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  _queryTravelVehicleParamCont({titleId}){
    let _this = this;
    return new Promise((resolve,reject) => {
      queryTravelVehicleParamCont({titleId: titleId,size: 99})
      .then(res => {
        if(res.success){
          resolve(res.data.content);
        }else{
          reject(res.errMessage);
        }
      })
    })
    // queryTravelVehicleParamCont({titleId: _this.data.paramTitleId,size: 99})
    // .then(res => {
    //   if(res.success){
    //     _this.setData({
    //       paramContList: res.data.content,
    //     })
    //   }else{
    //     wx.showToast({
    //       title: res.errMessage,
    //       icon: 'none',
    //     })
    //   }
    // })
  },
  // 初始数据处理
  initDataList(){
    let [top, typeTop] = [0, 0]
    const { paramTitleList } = this.data;
    let list = [];
    for (let index = 0; index < paramTitleList.length; index++) {
      const item = paramTitleList[index];
      var itmHeight = 0;
      for (let j = 0; j < item.children.length; j++) {
        const element = item.children[j];
        if(j%2 == 0){
          itmHeight += 48;
        }
      }
      itmHeight = itmHeight + 40
      item.height = itmHeight;
      item.top = {begin: top, end: top + itmHeight}
      item.typeTop = typeTop;
      top += itmHeight;
      typeTop += 100;
      list.push(item);
    }
    console.log(list,'list');
    this.setData({
      paramTitleList: list,
    })
    var activeKey = wx.getStorageSync('classifyId') ?? '';
    console.log(activeKey,'activeKey')
    setTimeout(()=> {
      this.setData({
        showGoodsBtmDom: true,
      },1000)
    })
  },
  handleScroll({detail}) {
    // wx.createSelectorQuery()
    // .select('.goodsWrapList')
    // .boundingClientRect((res) => {
    //   console.log(res.top,'top')
    //   console.log(event.detail.scrollTop,'scrollTop')
    //   this.setData({
    //     scrollTop: event.detail.scrollTop,
    //     offsetTop: res.top + this.data.CustomBar,
    //   });
    // })
    // .exec();
    // 每次滚动都需要循环匹配，找寻滚动条到达那个区域，匹配到了或者到最后了就停止，是真的蛋疼。
    for (let i = 0; i < this.data.paramTitleList.length; i += 1) {
      // 进入循环了，这个商品列表的数组是经过加工的，在初始化的时候计算了每个种类项区域（top）和左边标题（typeTop）离顶部距离。
      let v = this.data.paramTitleList[i]
      console.log(v,'item')
      // 如果滚动条与顶部的距离 >= 这一项开头的与顶部的距离 < 这一项结尾与顶部的距离，那么现在正显示的就是这个区域了。
      if (detail.scrollTop >= v.top.begin && detail.scrollTop < v.top.end) {
        // 记录下现在显示的是第几个区域。
        this.setData({
          activeKey: i,
          typeTop: v.typeTop,
        })
        // this.inScroll = i
        // // 位于商品栏区域上面的标题跟着变成现在显示的区域。
        // this.goodsType = v.title
        // // 左边标题栏也跟着滚动到，如果可以（看标题栏有多长囖），将对应的区域移到中间。
        // this.typeTop = v.typeTop
        // 匹配到了，并且做完该做的东西就跳出循环，免得他继续匹配。
        break
      }
    }
  },
  toScrollItem (e) {
    let index = e.detail;
    console.log(index,'index')
    this.setData({
      scrollTop: this.data.scrollTop += 0.00001
    })
    console.log('触发了toScrollItem')
    setTimeout(() => {
      this.setData({
        scrollTop: this.data.paramTitleList[index].top.begin
      })
    })
  },
  dropdownChange(e){
    console.log(e,'e')
    if(e.detail == 1){
      this.setData({
        sort: 'price',
        order: 'ASC'
      })
    }else{
      this.setData({
        sort: 'sort',
        order: ''
      })
    }
    this.initData();
  },
  // 选择车辆配置信息
  selParamCont(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    const { paramContId } = this.data;
    if(paramContId.indexOf(item.id) != -1){
      paramContId.splice(paramContId.indexOf(item.id),1)
    }else{
      paramContId.push(item.id);
    }
    this.setData({
      paramContId: paramContId,
    })
    console.log(paramContId,'paramContId')
  },
  // 重置车辆参数
  resetParam(){
    this.setData({
      paramContId: [],
      vehicleIds: '',
      classificationId: '',
      classifyIndex: 0,
    })
    this.initData()
    this.selectComponent('#item').toggle();
    
  },
  // 根据车辆参数获取车辆IDs
  submitParam(){
    let _this = this;
    queryTravelVehicleIdByParamContId({paramContentIds: _this.data.paramContId.join(',')})
    .then(res => {
      if(res.success){
        if(res.data.quantity == 0){
          wx.showToast({
            title: '暂未查询到符合条件车辆信息',
            icon: 'none',
          })
        }else{
          _this.setData({
            vehicleIds: res.data.vehicleIds,
          })
          _this.initData();
          _this.selectComponent('#item').toggle();
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取车辆分类信息
  getClassify(){
    let _this = this;
    queryTravelVehicleClassify({size: 99})
    .then(res => {
      if(res.success){
        let list = [];
        let minAmount = 0;
        for (let index = 0; index < res.data.content.length; index++) {
          const element = res.data.content[index];
          if((minAmount > element.minPrice && element.minPrice != 0)|| minAmount == 0 ){
            minAmount = element.minPrice;
          }
          list.push(element);
        }
        list.unshift({id: '', name: '全部车型',minPrice: minAmount});
        _this.setData({
          classifyList: list,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择车辆分类
  selClassify(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let index = e.target.dataset.index||e.currentTarget.dataset.index;
    this.setData({
      classificationId: item.isHot == '1' ? '' : item.id ,
      classifyIndex: index,
      isHot: item.isHot,
    })
    this.initData();
  },
  // 初始化车辆查询
  initData(){
    this.setData({
      page: 0,
      isReachBottom: false,
      noMore: false,
      loading: false,
      loadingFailed: false,
    })
    this.getData();
  },
  // 获取车辆数据
  getData(){
    let _this = this;
    queryTravelVehicleInfo({classificationId: _this.data.classificationId,vehicleIds: _this.data.vehicleIds,page: _this.data.page,isHot: _this.data.isHot == '1' ? '1': '',order: _this.data.order,sort: _this.data.sort})
    .then(res => {
      if(res.success){
        var list = _this.data.dataList;
        var arr = [];
        for (let index = 0; index < res.data.content.length; index++) {
          const item = res.data.content[index];
          item.instruction = item.instruction.replace(/,/g,'|');
          item.tagList = item.tag.split(',');
          arr.push(item);
        }
        if(_this.data.page == 0){
          list = arr;
        }else{
          list = list.concat(arr);
        }
        _this.setData({
          dataList: list,
          total: res.data.totalElements,
          page: _this.data.page+1,
        })
        if(_this.data.page * 10 >= res.data.totalElements){
          _this.setData({
            isReachBottom: false,
            noMore: true,
            loading: false,
            loadingFailed: false,
          })
        }else{
          _this.setData({
            isReachBottom: true,
            noMore: false,
            loading: false,
            loadingFailed: false,
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 跳转详情
  goDetail(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
      let url = e.target.dataset.name||e.currentTarget.dataset.name;
      wx.navigateTo({
        url: `${url}?item=${JSON.stringify(item)}`,
      })
  },
})